<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

use service\DataService;
use service\NodeService;
use think\Db;

/**
 * 打印输出数据到文件
 * @param mixed $data 输出的数据
 * @param bool $force 强制替换
 * @param string|null $file
 */
function p($data, $force = false, $file = null)
{
    is_null($file) && $file = env('runtime_path') . date('Ymd') . '.txt';
    $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
    $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
}

/**
 * RBAC节点权限验证
 * @param string $node
 * @return bool
 */
function auth($node)
{
    return NodeService::checkAuthNode($node);
}

/**
 * 设备或配置系统参数
 * @param string $name 参数名称
 * @param bool $value 默认是null为获取值，否则为更新
 * @return string|bool
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function sysconf($name, $value = null)
{
    static $config = [];
    if ($value !== null) {
        list($config, $data) = [[], ['name' => $name, 'value' => $value]];
        return DataService::save('SystemConfig', $data, 'name');
    }
    if (empty($config)) {
        $config = Db::name('SystemConfig')->column('name,value');
    }
    return isset($config[$name]) ? $config[$name] : '';
}

/**
 * 日期格式标准输出
 * @param string $datetime 输入日期
 * @param string $format 输出格式
 * @return false|string
 */
function format_datetime($datetime, $format = 'Y年m月d日 H:i:s')
{
    return date($format, strtotime($datetime));
}

/**
 * UTF8字符串加密
 * @param string $string
 * @return string
 */
function encode($string)
{
    list($chars, $length) = ['', strlen($string = iconv('utf-8', 'gbk', $string))];
    for ($i = 0; $i < $length; $i++) {
        $chars .= str_pad(base_convert(ord($string[$i]), 10, 36), 2, 0, 0);
    }
    return $chars;
}

/**
 * UTF8字符串解密
 * @param string $string
 * @return string
 */
function decode($string)
{
    $chars = '';
    foreach (str_split($string, 2) as $char) {
        $chars .= chr(intval(base_convert($char, 36, 10)));
    }
    return iconv('gbk', 'utf-8', $chars);
}

/**
 * 下载远程文件到本地
 * @param string $url 远程图片地址
 * @return string
 */
function local_image($url)
{
    return \service\FileService::download($url)['url'];
}

//验证手机号码
function is_mobile($tel){
    if (preg_match ( '/^(1(3|4|5|6|7|8|9)[0-9])\d{8}$/', $tel )) {
        return TRUE;
    } else {
        return FALSE;
    }
}

/**
 * 验证身份证号
 *
 * @param $vStr
 *
 * @return bool
 * changhui
 */
function isCreditNo($vStr)
{
    $vCity = ['11', '12', '13', '14', '15', '21', '22', '23',
              '31', '32', '33', '34', '35', '36', '37', '41', '42',
              '43', '44', '45', '46', '50', '51', '52', '53', '54',
              '61', '62', '63', '64', '65', '71', '81', '82', '91',
    ];

    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) {
        return false;
    }

    if (!in_array(substr($vStr, 0, 2), $vCity)) {
        return false;
    }

    $vStr    = preg_replace('/[xX]$/i', 'a', $vStr);
    $vLength = strlen($vStr);

    if ($vLength == 18) {
        $vBirthday = substr($vStr, 6, 4).'-'.substr($vStr, 10, 2).'-'.substr($vStr, 12, 2);
    }else {
        $vBirthday = '19'.substr($vStr, 6, 2).'-'.substr($vStr, 8, 2).'-'.substr($vStr, 10, 2);
    }

    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) {
        return false;
    }
    if ($vLength == 18) {
        $vSum = 0;

        for ($i = 17; $i >= 0; $i--) {
            $vSubStr = substr($vStr, 17 - $i, 1);
            $vSum    += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
        }

        if ($vSum % 11 != 1) {
            return false;
        }
    }

    return true;
}

/**
 * @param $mydate
 *
 * @return false|string
 */
function birthday($mydate){
    $birth = $mydate;
    list($by,$bm,$bd) = explode('-', $birth);
    $cm = date('n');
    $cd = date('j');
    $age = date('Y')-$by-1;
    if ($cm > $bm || $cm == $bm && $cd>$bd)
        $age++;
    return $age;
}
/**
 *  计算.星座
 *
 * @param int $month 月份
 * @param int $day 日期
 * @return str
 */
function get_constellation($month, $day){
    $signs = [
        ['20'=>'宝瓶座'], ['19'=>'双鱼座'],
        ['21'=>'白羊座'], ['20'=>'金牛座'],
        ['21'=>'双子座'], ['22'=>'巨蟹座'],
        ['23'=>'狮子座'], ['23'=>'处女座'],
        ['23'=>'天秤座'], ['24'=>'天蝎座'],
        ['22'=>'射手座'], ['22'=>'摩羯座']
    ];
    $key = (int)$month - 1;
    list($startSign, $signName) = each($signs[$key]);
    if( $day < $startSign ){
        $key = $month - 2 < 0 ? $month = 11 : $month -= 2;
        list($startSign, $signName) = each($signs[$key]);
    }
    return $signName;
}


/**
 * 格式化时间
 * @param        $time
 * @param string $format
 *
 * @return false|string
 */
function datetime($time, $format = 'Y-m-d H:i:s')
{
    $time = is_numeric($time) ? $time : strtotime($time);
    return $time ? date($format, $time) : '';
}

function cdnurl($url, $ext = '!100x80', $type = '')
{
    $url = $url ? $url.$ext : request()->domain().'/static/theme/img/default.jpg';
    return $url;
}

function human_date($remote, $local = null)
{
    $timediff = $remote - (is_null($local) || $local ? time() : $local);
    $chunks = [
        [60 * 60 * 24 * 365, '年'],
        [60 * 60 * 24 * 30, '个月'],
        [60 * 60 * 24, '天'],
        [60 * 60, '小时'],
        [60, '分钟']
    ];

    for ($i = 0, $j = count($chunks); $i < $j; $i++)
    {
        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];
        if (($count = floor($timediff / $seconds)) != 0)
        {
            break;
        }
    }
    return $count > 0 ? $count.$name : '';
}

function numberShow($number)
{
    if($number <= 0) {
        return 0;
    }
    if($number < 10000) {
        return $number;
    }else {
        return sprintf("%.1fW",$number / 10000);
    }
}

/**
 * url封装
 */
function resultUrl($url, $model = '@admin')
{
    list($base, $spm, $u) = [url($model), input('get.spm'), url($url)];
    return  "{$base}#{$u}?spm={$spm}";
}


/**
 * 批量移除数组中指定元素
 * @param $arr  待处理的数组
 * @param $keys 要保留的元素的键名的数组
 * @return mixed 处理后的数组
 */
function k_array_only($arr, $keys)
{
    $arr = array_filter($arr, function ($k) use ($keys) {
        if (in_array($k, $keys)) return true;
    }, ARRAY_FILTER_USE_KEY);
    return $arr;
}

/**
 * 批量移除数组中指定元素
 * @param $arr  待处理的数组
 * @param $keys 要排除掉的元素的键名的数组
 * @return mixed 处理后的数组
 */
function k_array_except($arr, $keys)
{
    $arr = array_filter($arr, function ($k) use ($keys) {
        if (!in_array($k, $keys)) return true;
    }, ARRAY_FILTER_USE_KEY);
    return $arr;
}

/**
 * 获取媒体资源完整的url地址
 * @param $v
 * @return string
 */
function getQiniuUrl($v){
    if ($v)
        return env('dns_resource') . '/' . trim($v, '/');
}

/**
 * 手机号掩码
 * @param $mobile
 * @return string
 */
function mobile_asterisk($mobile)
{
    $mobile_asterisk = substr($mobile,0,3)."****".substr($mobile,7,4);
    return $mobile_asterisk;
}

/**
 * 身份证掩码
 * @param $mobile
 * @return string
 */
function iden_card_asterisk($iden_card){
    $iden_card_asterisk = substr($iden_card,0,3)."******".substr($iden_card,7,4);
    return $iden_card_asterisk;
}

/**
 * 姓名掩码
 * @param $mobile
 * @return string
 */
function name_asterisk($name){
    $len = mb_strlen($name);
    $name_asterisk = mb_substr($name,0,1).str_repeat('*',$len-1);
    return $name_asterisk;
}

/**
 * 渠道ref生成方式
 * @param int $number 用户ID
 * @param string $prefix 前缀
 * @return bool
 */
function get_ref($uid = 0 , $prefix = 'SC'){
    if ($uid == 0) {
        return $prefix.'9'.substr(microtime(), 2, 2) . sprintf('%05d', rand(0, 999));
    } else {
        return $prefix . sprintf('%09d',$uid);
    }
}

/**
 * 生成宣传海报
 * @param array  参数,包括图片和文字
 * @param string  $filename 生成海报文件名,不传此参数则不生成文件,直接输出图片
 * @return [type] [description]
 */
function createPoster($config=array(),$filename=""){
    //如果要看报什么错，可以先注释调这个header
    if(empty($filename)) header("content-type: image/png");
    $imageDefault = array(
        'left'=>0,
        'top'=>0,
        'right'=>0,
        'bottom'=>0,
        'width'=>100,
        'height'=>100,
        'opacity'=>100
    );
    $textDefault = array(
        'text'=>'',
        'left'=>0,
        'top'=>0,
        'fontSize'=>32,       //字号
        'fontColor'=>'255,255,255', //字体颜色
        'angle'=>0,
    );
    $background = $config['background'];//海报最底层得背景
    //背景方法
    $backgroundInfo = getimagesize($background);
    $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
    $background = $backgroundFun($background);
    $backgroundWidth = imagesx($background);  //背景宽度
    $backgroundHeight = imagesy($background);  //背景高度
    $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
    $color = imagecolorallocate($imageRes, 0, 0, 0);
    imagefill($imageRes, 0, 0, $color);
    // imageColorTransparent($imageRes, $color);  //颜色透明
    imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
    //处理了图片
    if(!empty($config['image'])){
        foreach ($config['image'] as $key => $val) {
            $val = array_merge($imageDefault,$val);
            if($val['stream']){   //如果传的是字符串图像流
                $info = getimagesizefromstring($val['url']);
                $function = 'imagecreatefromstring';
            }else{
                $info = getimagesize($val['url']);
                $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
            }

            $res = $function($val['url']);
            $resWidth = $info[0];
            $resHeight = $info[1];
            //建立画板 ，缩放图片至指定尺寸
            $canvas=imagecreatetruecolor($val['width'], $val['height']);
            imagefill($canvas, 0, 0, $color);
            //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
            imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
            $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
            $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
            //放置图像
            imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左，上，右，下，宽度，高度，透明度
        }
    }
    //处理文字
    if(!empty($config['text'])){
        foreach ($config['text'] as $key => $val) {
            $val = array_merge($textDefault,$val);
            list($R,$G,$B) = explode(',', $val['fontColor']);
            $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
            $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
            $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
            imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
        }
    }
    //生成图片
    if(!empty($filename)){
        $res = imagejpeg ($imageRes,$filename,90); //保存到本地
        imagedestroy($imageRes);
        if(!$res) return false;
        return $filename;
    }else{
        imagejpeg ($imageRes);     //在浏览器上显示
        imagedestroy($imageRes);
    }
}

/**
 * 订单生成
 * @param string
 *
 * 直接购买 L
 * 游戏兑换 G
 * 套餐购买 T
 * 积分 C
 * 翻牌兑换 F
 * 翻牌充值 R
 * 提现编号 M
 * 活动兑换 H
 *
 * @return string
 */

function setOrderNumbber($type = 'D'){
    return  $type . date('Ymd') . substr(microtime(), 3, 5) . sprintf('%03d', rand(0, 999));
}

//获取毫秒级时间戳 13位
function getMillisecond() {
    list($msec, $sec) = explode(' ', microtime());
    $msec_format=sprintf("%'03s",round($msec*1000));
    return $sec.$msec_format;
}
//获取毫秒级时间(固定17位)
function getMillisecondFormat() {
    list($msec, $sec) = explode(' ', microtime());
    $msec_format=sprintf("%'03s",round($msec*1000));
    $msectime_format=date('YmdHis',$sec).$msec_format;
    return $msectime_format;
}